/*
 * Copyright kecp
 * Jun 02, 2010
 */
package Gui;

import LBS.EricssonLBS;
import LBS.Location;
import Tool.Debugger;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.PushRegistry;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.MessageListener;
import javax.wireless.messaging.TextMessage;
import traveller.Alarm;

/**
 * @author kecp
 */
public class testMIDlet extends MIDlet implements CommandListener ,MessageListener {

    private boolean midletPaused = false;
    Alarm alarm = null;
    MessageConnection msgconn;
    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Form MainForm;
    private Form AlarmForm;
    private TextBox logTextBox;
    private Command TestAlarm;
    private Command playCommand;
    private Command backCommand;
    private Command stopCommand;
    private Command exitCommand;
    private Command logCommand;
    private Command pushCommand;
    private Command cleanCommand;
    //</editor-fold>//GEN-END:|fields|0|

    /**
     * The testMIDlet constructor.
     */
    public testMIDlet() {
          Location.testDistance();
          Debugger.addDebugInfo("test log");
          System.out.println( Debugger.getLog() );
       //   EricssonLBS.testEriLBS();
        
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getMainForm());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
    //</editor-fold>//GEN-END:|3-startMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
    //</editor-fold>//GEN-END:|4-resumeMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
    //</editor-fold>//GEN-END:|5-switchDisplayable|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == AlarmForm) {//GEN-BEGIN:|7-commandAction|1|23-preAction
            if (command == backCommand) {//GEN-END:|7-commandAction|1|23-preAction
                // write pre-action user code here
                switchDisplayable(null, getMainForm());
                switchDisplayable(null, getMainForm());//GEN-LINE:|7-commandAction|2|23-postAction
                // write post-action user code here
            } else if (command == playCommand) {//GEN-LINE:|7-commandAction|3|21-preAction
                // write pre-action user code here
                alarm.play();
//GEN-LINE:|7-commandAction|4|21-postAction
                // write post-action user code here
            } else if (command == stopCommand) {//GEN-LINE:|7-commandAction|5|25-preAction
                // write pre-action user code here
                alarm.stop();
//GEN-LINE:|7-commandAction|6|25-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|7|18-preAction
        } else if (displayable == MainForm) {
            if (command == TestAlarm) {//GEN-END:|7-commandAction|7|18-preAction
                // write pre-action user code here
                switchDisplayable(null, getAlarmForm());//GEN-LINE:|7-commandAction|8|18-postAction
                // write post-action user code here
            } else if (command == exitCommand) {//GEN-LINE:|7-commandAction|9|27-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|10|27-postAction
                // write post-action user code here
                this.exitMIDlet();
            } else if (command == logCommand) {//GEN-LINE:|7-commandAction|11|29-preAction
                // write pre-action user code here
                updateLogText();
                switchDisplayable(null, getLogTextBox());//GEN-LINE:|7-commandAction|12|29-postAction
                // write post-action user code here
            } else if (command == pushCommand) {//GEN-LINE:|7-commandAction|13|36-preAction
                // write pre-action user code here
                setupListening();
//GEN-LINE:|7-commandAction|14|36-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|15|32-preAction
        } else if (displayable == logTextBox) {
            if (command == backCommand) {//GEN-END:|7-commandAction|15|32-preAction
                // write pre-action user code here
                switchDisplayable(null, getMainForm());//GEN-LINE:|7-commandAction|16|32-postAction
                // write post-action user code here
            } else if (command == cleanCommand) {//GEN-LINE:|7-commandAction|17|38-preAction
                // write pre-action user code here
                Debugger.cleanLog();
//GEN-LINE:|7-commandAction|18|38-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|19|7-postCommandAction
        }//GEN-END:|7-commandAction|19|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|20|
    //</editor-fold>//GEN-END:|7-commandAction|20|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: MainForm ">//GEN-BEGIN:|14-getter|0|14-preInit
    /**
     * Returns an initiliazed instance of MainForm component.
     * @return the initialized component instance
     */
    public Form getMainForm() {
        if (MainForm == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
            MainForm = new Form("form");//GEN-BEGIN:|14-getter|1|14-postInit
            MainForm.addCommand(getTestAlarm());
            MainForm.addCommand(getExitCommand());
            MainForm.addCommand(getLogCommand());
            MainForm.addCommand(getPushCommand());
            MainForm.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
        }//GEN-BEGIN:|14-getter|2|
        return MainForm;
    }
    //</editor-fold>//GEN-END:|14-getter|2|
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: AlarmForm ">//GEN-BEGIN:|16-getter|0|16-preInit
    /**
     * Returns an initiliazed instance of AlarmForm component.
     * @return the initialized component instance
     */
    public Form getAlarmForm() {
        if (AlarmForm == null) {//GEN-END:|16-getter|0|16-preInit
            // write pre-init user code here
            AlarmForm = new Form("Alarm");//GEN-BEGIN:|16-getter|1|16-postInit
            AlarmForm.addCommand(getPlayCommand());
            AlarmForm.addCommand(getBackCommand());
            AlarmForm.addCommand(getStopCommand());
            AlarmForm.setCommandListener(this);//GEN-END:|16-getter|1|16-postInit
            // write post-init user code here
            if( alarm == null ){
                alarm = new Alarm();
                alarm.createMedia();
            }
        }//GEN-BEGIN:|16-getter|2|
        return AlarmForm;
    }
    //</editor-fold>//GEN-END:|16-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: TestAlarm ">//GEN-BEGIN:|17-getter|0|17-preInit
    /**
     * Returns an initiliazed instance of TestAlarm component.
     * @return the initialized component instance
     */
    public Command getTestAlarm() {
        if (TestAlarm == null) {//GEN-END:|17-getter|0|17-preInit
            // write pre-init user code here
            TestAlarm = new Command("Alarm", Command.SCREEN, 0);//GEN-LINE:|17-getter|1|17-postInit
            // write post-init user code here
        }//GEN-BEGIN:|17-getter|2|
        return TestAlarm;
    }
    //</editor-fold>//GEN-END:|17-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: playCommand ">//GEN-BEGIN:|20-getter|0|20-preInit
    /**
     * Returns an initiliazed instance of playCommand component.
     * @return the initialized component instance
     */
    public Command getPlayCommand() {
        if (playCommand == null) {//GEN-END:|20-getter|0|20-preInit
            // write pre-init user code here
            playCommand = new Command("play", Command.SCREEN, 0);//GEN-LINE:|20-getter|1|20-postInit
            // write post-init user code here
        }//GEN-BEGIN:|20-getter|2|
        return playCommand;
    }
    //</editor-fold>//GEN-END:|20-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|22-getter|0|22-preInit
    /**
     * Returns an initiliazed instance of backCommand component.
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|22-getter|0|22-preInit
            // write pre-init user code here
            backCommand = new Command("\u540E\u9000", Command.BACK, 0);//GEN-LINE:|22-getter|1|22-postInit
            // write post-init user code here
        }//GEN-BEGIN:|22-getter|2|
        return backCommand;
    }
    //</editor-fold>//GEN-END:|22-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: stopCommand ">//GEN-BEGIN:|24-getter|0|24-preInit
    /**
     * Returns an initiliazed instance of stopCommand component.
     * @return the initialized component instance
     */
    public Command getStopCommand() {
        if (stopCommand == null) {//GEN-END:|24-getter|0|24-preInit
            // write pre-init user code here
            stopCommand = new Command("stop", Command.SCREEN, 0);//GEN-LINE:|24-getter|1|24-postInit
            // write post-init user code here
        }//GEN-BEGIN:|24-getter|2|
        return stopCommand;
    }
    //</editor-fold>//GEN-END:|24-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|26-getter|0|26-preInit
    /**
     * Returns an initiliazed instance of exitCommand component.
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|26-getter|0|26-preInit
            // write pre-init user code here
            exitCommand = new Command("\u9000\u51FA", Command.EXIT, 0);//GEN-LINE:|26-getter|1|26-postInit
            // write post-init user code here
        }//GEN-BEGIN:|26-getter|2|
        return exitCommand;
    }
    //</editor-fold>//GEN-END:|26-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: logCommand ">//GEN-BEGIN:|28-getter|0|28-preInit
    /**
     * Returns an initiliazed instance of logCommand component.
     * @return the initialized component instance
     */
    public Command getLogCommand() {
        if (logCommand == null) {//GEN-END:|28-getter|0|28-preInit
            // write pre-init user code here
            logCommand = new Command("\u65E5\u5FD7", Command.SCREEN, 0);//GEN-LINE:|28-getter|1|28-postInit
            // write post-init user code here
        }//GEN-BEGIN:|28-getter|2|
        return logCommand;
    }
    //</editor-fold>//GEN-END:|28-getter|2|
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: logTextBox ">//GEN-BEGIN:|30-getter|0|30-preInit
    /**
     * Returns an initiliazed instance of logTextBox component.
     * @return the initialized component instance
     */
    public TextBox getLogTextBox() {
        if (logTextBox == null) {//GEN-END:|30-getter|0|30-preInit
            // write pre-init user code here
            logTextBox = new TextBox("textBox", null, 100, TextField.ANY);//GEN-BEGIN:|30-getter|1|30-postInit
            logTextBox.addCommand(getBackCommand());
            logTextBox.addCommand(getCleanCommand());
            logTextBox.setCommandListener(this);//GEN-END:|30-getter|1|30-postInit
            // write post-init user code here
            logTextBox.setMaxSize(10000);
        }//GEN-BEGIN:|30-getter|2|
        return logTextBox;
    }
    //</editor-fold>//GEN-END:|30-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: pushCommand ">//GEN-BEGIN:|35-getter|0|35-preInit
    /**
     * Returns an initiliazed instance of pushCommand component.
     * @return the initialized component instance
     */
    public Command getPushCommand() {
        if (pushCommand == null) {//GEN-END:|35-getter|0|35-preInit
            // write pre-init user code here
            pushCommand = new Command("\u63A8\u5165", Command.SCREEN, 0);//GEN-LINE:|35-getter|1|35-postInit
            // write post-init user code here
        }//GEN-BEGIN:|35-getter|2|
        return pushCommand;
    }
    //</editor-fold>//GEN-END:|35-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: cleanCommand ">//GEN-BEGIN:|37-getter|0|37-preInit
    /**
     * Returns an initiliazed instance of cleanCommand component.
     * @return the initialized component instance
     */
    public Command getCleanCommand() {
        if (cleanCommand == null) {//GEN-END:|37-getter|0|37-preInit
            // write pre-init user code here
            cleanCommand = new Command("\u6E05\u9664", Command.SCREEN, 0);//GEN-LINE:|37-getter|1|37-postInit
            // write post-init user code here
        }//GEN-BEGIN:|37-getter|2|
        return cleanCommand;
    }
    //</editor-fold>//GEN-END:|37-getter|2|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

      private void updateLogText() {

        String log = Debugger.getLog();
        if( log != null ) {
            getLogTextBox().setString(log);
        }
    }

       public void setupListening()
    {
//        try {
//            //    try{
//            PushRegistry.registerConnection("cbs://:50", this.getClass().getName(), "*");
//        } catch (ClassNotFoundException ex) {
//            ex.printStackTrace();
//            Debugger.addDebugInfo(ex, "1");
//        } catch (IOException ex) {
//            ex.printStackTrace();
//            Debugger.addDebugInfo(ex, "2");
//        }
//               //  PushRegistry.registerConnection("cbs://:50","Gui.MainMIDlet","*");
//          //  }catch(Exception e){ Debugger.addDebugInfo(e, this.getClass().getName()+" setup cbs");}
//            String[] connList;
//            connList = PushRegistry.listConnections(true);
//            if((connList == null) || (connList.length == 0))
//            {
//              // You can exit the app, if you want
//                Debugger.addDebugInfo( "connlist null");
//            }
//            else
            {
                try{
                    msgconn = (MessageConnection)Connector.open("cbs://:50", Connector.READ);
                    msgconn.setMessageListener(this);
                    Debugger.addDebugInfo("setup cbs succeed");
                } catch( IOException e){
                    e.printStackTrace();
                    Debugger.addDebugInfo(e, "setup cbs");
                }
             }
    }

    public void notifyIncomingMessage(MessageConnection conn)
    {
        TextMessage txtmsg = null;
      try{
            txtmsg =(TextMessage)msgconn.receive();
      }catch(Exception e){System.out.println(e);}
      String from = txtmsg.getAddress();
      String Msg = txtmsg.getPayloadText();
      Debugger.addDebugInfo("from:" + from);
      Debugger.addDebugInfo("Msg:" + Msg);
      // Display from & Msg
    }
}
